package com.xhu.collegestudentrentalsystem.interceptor;

import com.xhu.collegestudentrentalsystem.annocation.LoginRequired;
import com.xhu.collegestudentrentalsystem.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zhu huilin
 * @date 2023/3/6 19:59
 *  对用户部分请求路径进行拦截（尤其是需要用到用户登录数据的请求），判断是否登录
 */
@Component
public class LoginRequireInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);

            /*
                如果取到注解不为空，则用户需要登录
                    （1）当前用户为空，跳转登录页面；（2）当前用户不为空，正常访问
             */
            if(loginRequired != null & hostHolder.getUser() == null){
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
